package com.snakegame.service;

import com.snakegame.dto.RegisterRequest;
import com.snakegame.entity.User;
import com.snakegame.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public User registerUser(RegisterRequest registerRequest) {
        if (userRepository.existsByUsername(registerRequest.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
        user.setHighestScore(0);

        return userRepository.save(user);
    }

    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    public User updateHighestScore(String username, Integer newScore) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        if (newScore > user.getHighestScore()) {
            user.setHighestScore(newScore);
            return userRepository.save(user);
        }
        
        return user;
    }

    public List<User> getTopUsers() {
        return userRepository.findTopUsersByHighestScore();
    }

    public boolean existsByUsername(String username) {
        return userRepository.existsByUsername(username);
    }
}